import { Meteor } from 'meteor/meteor'

import "./login.html";


Template.login.onCreated(function () {
     Meteor.subscribe('roles', {}, {sort: {name: 1}});

     $('head').append('<link rel="stylesheet" type="text/css" href="assets/css/Login-Form-Dark.css">');
});

Template.login.onRendered(function () {

     $('head').append('<link rel="stylesheet" href="assets/css/Login-Form-Dark.css">');
});


Template.login.events({
  'submit form'(event, instance) {
  	event.preventDefault();
     UIBlock.block('正在登录，请稍后');
  	let email_jquery = "[name='email']";
  	let password_jquery = "[name='password']";

  	let email = $(email_jquery).val();
  	let password = $(password_jquery).val();

      Meteor.subscribe('MobileUserName', email, {onReady: function(){
        console.log('subscribe is ready');
        console.log(email);
        let userObj =  Meteor.users.find({profile: {mobile: email}}).fetch()[0];
        console.log(userObj);

        if (userObj != undefined ) {
           if( userObj.profile.mobile == email){
            email = userObj.username
            console.log(email);
          }
        }
       
        Meteor.loginWithPassword(email, password, function(error){
              UIBlock.unblock();
              if (error) {
                if (error.reason == "Match failed") {
                FlashMessages.sendError("密码或其他信息错误");

                return false;
               }
               if (error.reason == "Incorrect password") {
                FlashMessages.sendError("密码错误");

                return false;
               }
               if (error.reason == "User not found") {
                FlashMessages.sendError("用户不存在");

                return false;
               }

              }else{

                  FlowRouter.go('App.admin');
                  FlashMessages.sendSuccess("登录成功");
              }



            });
      }
    });


    // increment the counter when button is clicked
    // instance.counter.set(instance.counter.get() + 1);
  },

});
